package servlets;

import java.io.IOException;
import java.util.Hashtable;
import java.util.Set;

import javax.naming.Context;
import javax.naming.InitialContext;
import javax.servlet.RequestDispatcher;
import javax.servlet.ServletException;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import ejbSessions.ManagerAmicizieRemote;
import ejbSessions.ManagerUtenteRemote;
import EJBPackage.RichiestaAmicizia;
import EJBPackage.Utente;
/**
 * Servlet implementation class Amici
 */
public class Amici extends HttpServlet {
	private static final long serialVersionUID = 1L;
       
    /**
     * @see HttpServlet#HttpServlet()
     */
    public Amici() {
        super();
        // TODO Auto-generated constructor stub
    }

	/**
	 * @see HttpServlet#doGet(HttpServletRequest request, HttpServletResponse response)
	 */
	protected void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
		gestisciRichiesta(request, response);
	}

	/**
	 * @see HttpServlet#doPost(HttpServletRequest request, HttpServletResponse response)
	 */
	protected void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
		gestisciRichiesta(request, response);
	}
	
	private void gestisciRichiesta(HttpServletRequest request, HttpServletResponse response){
		RequestDispatcher dispatcher = request.getRequestDispatcher("/Utente/Amici.jsp");
		int idUtente;
		Set<Utente> amici;
		Set<RichiestaAmicizia> richiesteAmicizia;
		try{
			Hashtable<String,String> env = new Hashtable<String,String>();
			env.put(Context.INITIAL_CONTEXT_FACTORY, "org.jnp.interfaces.NamingContextFactory");
			env.put(Context.PROVIDER_URL,"localhost:1099");
			InitialContext jndiContext = new InitialContext(env);
			Object ref = jndiContext.lookup("ManagerUtente/remote");
			ManagerUtenteRemote manager = (ManagerUtenteRemote)ref;
	
			idUtente = (Integer)request.getSession().getAttribute("userid");
	
			amici = manager.getAmici(idUtente);
			richiesteAmicizia = manager.getUtente(idUtente).getRichiesteAmiciziaRicevute();
			request.getSession().setAttribute("amici", amici);
			request.getSession().setAttribute("richieste", richiesteAmicizia);
			
		}catch (Exception e) {
			
		}
		
		try {
			dispatcher.forward(request, response);
		} catch (ServletException e) {
			e.printStackTrace();
		} catch (IOException e) {
			e.printStackTrace();
		}
	}

}
